package com.ihighest.app.infox.adapter;

import io.rong.imkit.RongIM;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.AgriculturalTechnologyActivity;
import com.ihighest.app.infox.activity.LoginActivity;
import com.ihighest.app.infox.activity.SettingActivity;
import com.ihighest.app.infox.activity.UserDetailActivity;
import com.umeng.socialize.utils.Log;

public class QuestionContentListViewAdapter extends BaseAdapter {

	protected static final String TAG = "QuestionContentListViewAdapter";
	private final LayoutInflater inflater;
	Context context;
	JSONArray jsonArray;

	String id;// 回答id
	String qid;// 问题id
	String uid; // account id
	String uname;
	String rid;

	private boolean canadopt = true;

	ArrayList<Integer> agreelist;
	ArrayList<Integer> disagreelist;

	public QuestionContentListViewAdapter(Context context, JSONArray jsonArray, String qid, String uid, String uname, String rid) {
		super();
		this.context = context;
		this.jsonArray = jsonArray;
		this.qid = qid;
		this.uid = uid;
		this.uname = uname;
		this.rid = rid;
		inflater = LayoutInflater.from(context);
		agreelist = new ArrayList<>();
		disagreelist = new ArrayList<Integer>();
	}

	@Override
	public int getCount() {
		return jsonArray != null ? jsonArray.length() : 0;
	}

	@Override
	public Object getItem(int arg0) {
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public View getView(final int position, View view, ViewGroup arg2) {
		final ViewHolder holder;
		if (view == null) {
			holder = new ViewHolder();
			view = inflater.inflate(R.layout.infox_activity_questioncontentactivity_listviewitem, null);

			holder.item_icon = (ImageView) view.findViewById(R.id.id_icon);
			holder.item_type = (TextView) view.findViewById(R.id.id_type);
			holder.item_name = (TextView) view.findViewById(R.id.id_name);

			holder.item_time = (TextView) view.findViewById(R.id.id_time);
			holder.item_image = (ImageView) view.findViewById(R.id.id_imageview);
			holder.item_righttextview = (TextView) view.findViewById(R.id.id_adopted_text);
			holder.item_tv_content = (TextView) view.findViewById(R.id.tv_content);
			holder.item_iv_content = (ImageView) view.findViewById(R.id.iv_content);
			holder.item_stilaskicon = (ImageView) view.findViewById(R.id.id_stileaskimage);
			holder.item_stilask = (TextView) view.findViewById(R.id.id_stileasktextview);
			holder.item_agree = (ImageView) view.findViewById(R.id.id_agreeimage);
			holder.item_agreetextview = (TextView) view.findViewById(R.id.id_agree_textview);

			holder.item_disagree = (ImageView) view.findViewById(R.id.id_disagreeimage);
			holder.item_disagreetextview = (TextView) view.findViewById(R.id.id_disagreetextview);

			holder.item_asklayout = (LinearLayout) view.findViewById(R.id.id_asklayout);
			holder.item_goodlayout = (LinearLayout) view.findViewById(R.id.id_goodlayout);
			holder.item_notgoodlayout = (LinearLayout) view.findViewById(R.id.id_notgoodlayout);
			holder.rankingImg = (ImageView) view.findViewById(R.id.id_userRankImg);
			holder.voice = (TextView) view.findViewById(R.id.voiceContent);

			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		String iconurl = null;
		try {
			id = jsonArray.getJSONObject(position).getString("id");
			iconurl = jsonArray.getJSONObject(position).getJSONObject("answer").getString("image");
			String type = jsonArray.getJSONObject(position).getJSONObject("answer").getString("type");

			if ("Specialist".equalsIgnoreCase(type)) {

				if (!TextUtils.isEmpty(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rank"))) {

					holder.item_type.setText(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rank"));
					holder.item_type.setVisibility(View.VISIBLE);
				}

				if (!TextUtils.isEmpty(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rankImage"))) {

					AppKit.SetUserImg(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rankImage"), holder.rankingImg);
					holder.rankingImg.setVisibility(View.VISIBLE);
				}
			} else {
				holder.item_type.setVisibility(View.INVISIBLE);
				holder.rankingImg.setVisibility(View.INVISIBLE);
			}

			// if ("Regular".equalsIgnoreCase(type)) {
			// holder.item_type.setText("会员");
			// } else if ("Specialist".equalsIgnoreCase(type)) {
			// holder.item_type.setText(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rank"));
			//
			// if
			// (!TextUtils.isEmpty(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rankImage")))
			// {
			// // DisplayImageOptions defaultOptions = new
			// // DisplayImageOptions.Builder()
			// //
			// .showImageForEmptyUri(R.drawable.infox_person_no_icon).showImageOnFail(R.drawable.infox_person_no_icon)
			// //
			// .showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true).cacheOnDisc(true).build();
			// // ImageLoader.getInstance().displayImage(
			// //
			// jsonArray.getJSONObject(position).getJSONObject("answer").getString("rankImage"),
			// // holder.rankingImg,
			// // defaultOptions);
			// AppKit.SetUserImg(jsonArray.getJSONObject(position).getJSONObject("answer").getString("rankImage"),
			// holder.rankingImg);
			//
			// }
			// } else if ("Enterprise".equalsIgnoreCase(type)) {
			// holder.item_type.setText("企业会员");
			// } else if ("Outlet".equalsIgnoreCase(type)) {
			// holder.item_type.setText("农资店主");
			// }

			String name = jsonArray.getJSONObject(position).getJSONObject("answer").getString("title");
			if (name.length() >= 6) {
				holder.item_name.setText(name.substring(0, 6) + "...");
			} else {

				holder.item_name.setText(name);
			}

			holder.item_time.setText(AppKit.timeToBeforeStr(jsonArray.getJSONObject(position).getLong("time")));

			holder.item_righttextview.setTag(id);
			holder.item_goodlayout.setTag(id);
			holder.item_notgoodlayout.setTag(id);

			if (SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID, "").equalsIgnoreCase(uid)) {
				holder.item_asklayout.setVisibility(View.VISIBLE);
				holder.item_asklayout.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
							((Activity) context).startActivity(new Intent(context, LoginActivity.class));
						} else {
							try {
								Const.IM_EXTRA = "chat_issue_ask:" + qid + ":"
										+ jsonArray.getJSONObject(position).getJSONObject("answer").getString("mid") + ":"
										+ SharedPreferencesKit.getString(context, Const.SP_KEY_USER_MID);
								RongIM.getInstance().startPrivateChat(context,
										jsonArray.getJSONObject(position).getJSONObject("answer").getString("rid"),
										"[" + uname + "]" + "的提问");
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				});
			} else {
				holder.item_asklayout.setVisibility(View.INVISIBLE);
			}
			String answerstate = jsonArray.getJSONObject(position).getString("state");
			if (answerstate.equals("false")) {
				holder.item_righttextview.setBackgroundResource(R.drawable.infox_question_green);
				holder.item_righttextview.setTextColor(context.getResources().getColor(R.color.resolve_color));
				holder.item_righttextview.setText("采纳");
				holder.item_image.setVisibility(View.GONE);
				if (SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID, "").equalsIgnoreCase(uid)) {

					holder.item_righttextview.setVisibility(View.VISIBLE);
					holder.item_righttextview.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(final View arg0) {
							// jianqun

							if (canadopt) {
								
								
								new AlertDialog.Builder(context).setMessage("此答案是否解决了您的问题")// 设置显示的内容

								.setPositiveButton("否", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										// 确定按钮的响应事件
										
										
									}

								}).setNegativeButton("是", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										canadopt = false;
										adopt(arg0.getTag().toString(), qid);
										holder.item_righttextview.setText("已采纳");
										holder.item_righttextview.setTextColor(context.getResources().getColor(R.color.adopted_color));
										holder.item_image.setVisibility(View.VISIBLE);
										holder.item_righttextview.setBackgroundResource(R.drawable.infox_question_white);
									}

								}).show();// 在按键响应事件中显示此对话框
								
//								adopt(arg0.getTag().toString(), qid);
//								holder.item_righttextview.setText("已采纳");
//								holder.item_righttextview.setTextColor(context.getResources().getColor(R.color.adopted_color));
//								holder.item_image.setVisibility(View.VISIBLE);
//								holder.item_righttextview.setBackgroundResource(R.drawable.infox_question_white);
							} else {
								ToastKit.showShort(context, "已有采纳");
							}
						}
					});
				} else {
					holder.item_righttextview.setVisibility(View.GONE);// 不是自己提出的问题，不允许采纳
				}

			} else {
				holder.item_righttextview.setVisibility(view.VISIBLE);
				holder.item_righttextview.setText("已采纳");
				holder.item_righttextview.setBackgroundResource(R.drawable.infox_question_white);
				canadopt = false;
				holder.item_righttextview.setTextColor(context.getResources().getColor(R.color.adopted_color));
				holder.item_image.setVisibility(View.VISIBLE);
			}

			String content = jsonArray.getJSONObject(position).getString("content");
			if (content.startsWith("SYS__VOICE:::")) {
				// 语音 amr
				holder.voice.setVisibility(View.VISIBLE);

				String voiceUrl = content.replace("SYS__VOICE:::", "");
				if (voiceUrl.lastIndexOf(":") > 10) {
					holder.voice.setText(voiceUrl.substring(voiceUrl.lastIndexOf(":") + 1) + "″");
					voiceUrl = voiceUrl.substring(0, voiceUrl.lastIndexOf(":"));
				}
				holder.voice.setTag(R.id.tag_1, voiceUrl);
				holder.voice.setTag(R.id.tag_2, true);
				holder.voice.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(final View arg0) {
						if ((Boolean) arg0.getTag(R.id.tag_2)) {
							arg0.setTag(R.id.tag_2, false);
							Uri uri = Uri.parse((String) arg0.getTag(R.id.tag_1));
							MediaPlayer player = MediaPlayer.create(context, uri);
							player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
								@Override
								public void onCompletion(MediaPlayer p) {
									p.release();
									arg0.setTag(R.id.tag_2, true);
								}
							});
							player.start();
						}
					}
				});
			} else if (content.startsWith("SYS__IMAGE:::")) {
				// 图片
				holder.item_iv_content.setVisibility(View.VISIBLE);
				holder.item_iv_content.setTag(content.replace("SYS__IMAGE:::", ""));
				// DisplayImageOptions defaultOptions = new
				// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_img_loadrong)
				// .showImageOnFail(R.drawable.infox_img_loadrong).showImageOnLoading(R.drawable.infox_img_loadrong)
				// .cacheInMemory(true).cacheOnDisc(true).build();
				// ImageLoader.getInstance().displayImage(content.replace("SYS__IMAGE:::",
				// ""), holder.item_iv_content, defaultOptions);
				//
				AppKit.SetNormalImg(content.replace("SYS__IMAGE:::", ""), holder.item_iv_content);

				holder.item_iv_content.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						String url = (String) arg0.getTag();
						if (!TextUtils.isEmpty(url)) {
							AppKit.showBigImageView(context, url);
						}
					}
				});

			} else if (content.startsWith("SYS__TEXT:::")) {
				// 文本
				holder.item_tv_content.setVisibility(View.VISIBLE);
				holder.item_tv_content.setText(content.replace("SYS__TEXT:::", ""));
			} else if (content.startsWith("SYS__LOC:::")) {
				// 位置： latitude:longitude:poi
				holder.item_tv_content.setVisibility(View.VISIBLE);
				holder.item_tv_content.setText("地图功能正在建设中");
			}

			int agree = jsonArray.getJSONObject(position).getInt("agree");
			int unagree = jsonArray.getJSONObject(position).getInt("unagree");
			boolean canagree = jsonArray.getJSONObject(position).getBoolean("canagree");
			holder.item_agreetextview.setTag(R.id.tag_first, agree);
			holder.item_disagreetextview.setTag(R.id.tag_first, unagree);

			holder.item_agreetextview.setText(agree + "同意");
			holder.item_disagreetextview.setText(unagree + "不同意");
			if (!TextUtils.isEmpty(jsonArray.getJSONObject(position).getString("meagree"))) {
				if (Boolean.valueOf(jsonArray.getJSONObject(position).getString("meagree"))) {
					holder.item_agree.setImageResource(R.drawable.infox_good_press);
					holder.item_disagree.setImageResource(R.drawable.infox_notgood);

				} else {
					holder.item_agree.setImageResource(R.drawable.infox_good);
					holder.item_disagree.setImageResource(R.drawable.infox_notgood_press);
				}
			} else {
				holder.item_agree.setImageResource(R.drawable.infox_good);
				holder.item_disagree.setImageResource(R.drawable.infox_notgood);
			}

			holder.item_agreetextview.setTag("");
			holder.item_disagreetextview.setTag("");

			for (int i = 0; i < agreelist.size(); i++) {

				if (position == agreelist.get(i)) {

					agree = agree + 1;
					holder.item_agreetextview.setText(agree + "同意");
					holder.item_agree.setImageResource(R.drawable.infox_good_press);
					canagree = false;
				}

			}

			for (int i = 0; i < disagreelist.size(); i++) {

				if (position == disagreelist.get(i)) {

					unagree = unagree + 1;
					holder.item_disagreetextview.setText(unagree + "不同意");
					holder.item_disagree.setImageResource(R.drawable.infox_notgood_press);
					canagree = false;
				}

			}

			holder.item_agreetextview.setTag(canagree);
			holder.item_disagreetextview.setTag(canagree);

			// holder.item_agree.setTag(id);
			// holder.item_disagree.setTag(id);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}

		holder.item_agree.setTag("");
		holder.item_disagree.setTag("");

		holder.item_goodlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
					ToastKit.showShort(context, Const.UN_LOGIN_ALERT);
					Intent intent = new Intent(context, LoginActivity.class);
					context.startActivity(intent);
					return;
				}

				if ((boolean) holder.item_agreetextview.getTag()) {
					if (!holder.item_agree.getTag().equals("agreepress")) {

						submitagree((String) holder.item_goodlayout.getTag(), "1");
						int agree = (int) holder.item_agreetextview.getTag(R.id.tag_first);
						agree = agree + 1;
						holder.item_agreetextview.setText(agree + "同意");
						holder.item_agree.setImageResource(R.drawable.infox_good_press);
						holder.item_agree.setTag("agreepress");

						agreelist.add(position);
						// holder.item_agreetextview.setTag(position);// 是否操作过
						// holder.item_goodlayout.setTag(1, "press");// 点击状态
						// holder.item_goodlayout.setTag(2, agree);// 点击后人数

						// } else {
						// // 取消同意
						// System.out.println("取消同意");
					}

				} else {
					ToastKit.showShort(context, "您已进行评价");
				}

				holder.item_agreetextview.setTag(false);
				holder.item_disagreetextview.setTag(false);
				// canagree = false;

			}

		});

		holder.item_notgoodlayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
					ToastKit.showShort(context, Const.UN_LOGIN_ALERT);
					Intent intent = new Intent(context, LoginActivity.class);
					context.startActivity(intent);
					return;
				}

				if ((boolean) holder.item_disagreetextview.getTag()) {

					if (!holder.item_disagree.getTag().equals("disagreepress")) {
						submitagree((String) holder.item_notgoodlayout.getTag(), "2");
						int unagree = (int) holder.item_disagreetextview.getTag(R.id.tag_first);
						unagree = unagree + 1;
						holder.item_disagreetextview.setText(unagree + "不同意");
						holder.item_disagree.setImageResource(R.drawable.infox_notgood_press);
						holder.item_disagree.setTag("disagreepress");
						disagreelist.add(position);
						// holder.item_disagreetextview.setTag(position);
						// holder.item_notgoodlayout.setTag(1, "press");
						// holder.item_notgoodlayout.setTag(2, unagree);

						// } else {
						// // 取消不同意
						// System.out.println("取消不同意");

					}
				} else {
					ToastKit.showShort(context, "您已进行评价");
				}
				holder.item_agreetextview.setTag(false);
				holder.item_disagreetextview.setTag(false);
				// canagree = false;

			}
		});
		holder.item_icon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, UserDetailActivity.class);

				try {
					intent.putExtra("userId", jsonArray.getJSONObject(position).getJSONObject("answer").getString("uid"));
					context.startActivity(intent);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		// DisplayImageOptions defaultOptions = new
		// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_person_no_icon)
		// .showImageOnFail(R.drawable.infox_person_no_icon).showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true)
		// .cacheOnDisc(true).build();
		// ImageLoader.getInstance().displayImage(iconurl, holder.item_icon,
		// defaultOptions);
		AppKit.SetUserImg(iconurl, holder.item_icon);

		return view;
	}

	/**
	 * 
	 * 提交采纳信息
	 * 
	 * 
	 * @author yyh Created at 2015-11-2 上午10:29:31
	 */
	protected void adopt(String id, String qid) {
		Api.post("qa/accept", ApiParam.create().addParam("id", id).addParam("qid", qid), new ApiCallback(context, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					Log.e("questioncontent", "采纳ok");
					// 采纳成功发广播更新我的问题界面
					Intent intent = new Intent();
					intent.setAction(Const.REFLASH);
					context.sendBroadcast(intent);
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
			}
		}, context);

	}

	/**
	 * 
	 * 提交评价
	 * 
	 * 1采纳2不采纳
	 * 
	 * @author yyh Created at 2015-10-27 上午11:21:44
	 */

	protected void submitagree(String id, String action) {

		Api.post("qa/agree", ApiParam.create().addParam("id", id).addParam("action", action), new ApiCallback(context, true) {

			@Override
			public void handleSuccess(ApiResult result) {
			}

			@Override
			public void handleFailure(Exception e, String msg) {
			}
		}, context);

	}

	class ViewHolder {

		ImageView item_icon;
		TextView item_type;
		TextView item_name;

		TextView item_time;
		ImageView item_image;
		TextView item_righttextview;

		TextView item_tv_content;
		ImageView item_iv_content;

		ImageView item_stilaskicon;
		TextView item_stilask;
		ImageView item_agree;
		TextView item_agreetextview;

		ImageView item_disagree;
		TextView item_disagreetextview;
		LinearLayout item_asklayout;
		LinearLayout item_goodlayout;
		LinearLayout item_notgoodlayout;
		ImageView rankingImg;// 专家等级图片
		TextView voice;// 语音消息
	}

}
